package com.yulang.userapi.filter;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yulang.userapi.pojo.User;
import com.yulang.userapi.service.UserService;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * basic认证
 */
@Component
public class BasicAuthFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isNotEmpty(authorization)){
            String token64 = StringUtils.substringAfter(authorization,"Basic ");
            String token = new String(Base64Utils.decodeFromString(token64));
            String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(token,":");
            String username = items[0];
            String password = items[1];
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("name",username);
            val one = userService.getOne(query);
            if(one==null){
                response.setStatus(HttpStatus.FORBIDDEN.value());
                response.getWriter().write("用户不存在!");
                response.getWriter().flush();
                return;
            }else{
                if (one.getPassword().equals(password)) {
                    request.setAttribute("user",one);
                }else{
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    response.getWriter().write("用户不存在!");
                    response.getWriter().flush();
                    return;
                }
            }
        }
        chain.doFilter(request,response);
    }
}
